package net.zoneland.knowledge.service.impl;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.EsQuestionUtils;
import net.zoneland.knowledge.config.EsConfigInterface;
import net.zoneland.knowledge.constant.FieldConstant;
import net.zoneland.knowledge.constant.SystemConstant;
import net.zoneland.knowledge.enums.OperatorTypeEnum;
import net.zoneland.knowledge.model.Chat;
import net.zoneland.knowledge.model.EsQuestion;
import net.zoneland.knowledge.model.QaQueryDto;
import net.zoneland.knowledge.service.EsService;
import net.zoneland.knowledge.utils.ElasticSearchPoolUtil;
import net.zoneland.knowledge.utils.EsQueryUtils;
import net.zoneland.knowledge.utils.GsonUtils;
import net.zoneland.knowledge.utils.ResponseUtils;

/**
 * .
 *
 * @author: bcc
 *     2022/4/2
 */
@Service
public class EsServiceImpl implements EsService {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(EsServiceImpl.class);

    @Autowired
    private EsConfigInterface esConfig;

    @Override
    public void checkHealth(EsConfigInterface esConfig) throws Exception {
        try (RestHighLevelClient client = ElasticSearchPoolUtil.getClient()) {
            SearchRequest searchRequest = new SearchRequest(esConfig.getIndexName());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.size(0);
            searchRequest.source(searchSourceBuilder);
            client.search(searchRequest, RequestOptions.DEFAULT);
        }
    }

    @Override
    public List<String> dealBatch(final List<EsQuestion> list) throws Exception {
        BulkRequest request = new BulkRequest();
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        List<String> rs = new ArrayList<>();
        int count = 0;
        try {
            for (EsQuestion esQuestion : list) {
                count++;
                EsQuestionUtils.fillInfo(esQuestion);
                LOGGER.info("es Object:{}", esQuestion.toString());
                if (OperatorTypeEnum.DELETE == esQuestion.getOperation()) {
                    DeleteRequest deleteRequest = new DeleteRequest(esConfig.getIndexName(), esQuestion.getId());
                    request.add(deleteRequest);
                } else {
                    esQuestion.setUpdateTime(new Date());
                    IndexRequest indexRequest = new IndexRequest(esConfig.getIndexName());
                    indexRequest.id(esQuestion.getId());
                    request.add(indexRequest.source(GsonUtils.GSON.toJson(esQuestion), XContentType.JSON));
                }
                if (count % 500 == 0) {
                    final BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
                    rs.addAll(checkBulkResponse(bulkResponse));
                    count = 0;
                    request = new BulkRequest();
                }
            }
            if (count > 0) {
                final BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
                rs.addAll(checkBulkResponse(bulkResponse));
            }
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        return rs;
    }

    @Override
    public EsQuestion getById(final String id) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        try {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(esConfig.getIndexName());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.termQuery(FieldConstant.FIELD_ES_ID, id));
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            if(ArrayUtils.isNotEmpty(search.getHits().getHits())) {
                SearchHit searchHit = search.getHits().getAt(0);
                String qaString = searchHit.getSourceAsString();
                EsQuestion esQuestion = GsonUtils.GSON.fromJson(qaString, EsQuestion.class);
                return esQuestion;
            }
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        return null;
    }

    @Override
    public List<EsQuestion> getValidEsQuestionByIds(final List<String> ids) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        //只查询题库状态正常的数据
        boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
        boolqueryBuilder.must(QueryBuilders.termsQuery(FieldConstant.FIELD_ES_ID, ids));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getIndexName());
        searchRequest.source(sourceBuilder);
        SearchResponse search;
        try {
            search = client.search(searchRequest,RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest,RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        SearchHits hits1 = search.getHits();
        return ResponseUtils.esResultToList(hits1);
    }

    @Override
    public List<EsQuestion> queryByPath(final QaQueryDto qaQueryDto) throws Exception {
        {
            RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
            BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
            //只查询题库状态正常的数据
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_CATEGORY, qaQueryDto.getCategory()));
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL1TITLE2, qaQueryDto.getLevel1Title()));
            if (StringUtils.isNotBlank(qaQueryDto.getLevel2Title())) {
                boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL2TITLE2, qaQueryDto.getLevel2Title()));
            }
            if (StringUtils.isNotBlank(qaQueryDto.getLevel3Title())) {
                boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL3TITLE2, qaQueryDto.getLevel3Title()));
            }
            EsQueryUtils.appendDeptQuery(boolqueryBuilder, qaQueryDto);
            EsQueryUtils.appendRoleQuery(boolqueryBuilder, qaQueryDto);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.size(SystemConstant.DEFAULT_PAGE_SIZE);
            sourceBuilder.from(0);
            sourceBuilder.query(boolqueryBuilder);
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(esConfig.getIndexName());
            sourceBuilder.sort(FieldConstant.FIELD_ORDER, SortOrder.ASC);
            searchRequest.source(sourceBuilder);
            SearchResponse search = null;
            try {
                search = client.search(searchRequest, RequestOptions.DEFAULT);
            } catch (Exception e) {
                // 防止安全认证失败重试一次
                search = client.search(searchRequest, RequestOptions.DEFAULT);
            } finally {
                ElasticSearchPoolUtil.returnClient(client);
            }
            SearchHits hits1 = search.getHits();

            return ResponseUtils.esResultToList(hits1);
        }
    }

    @Override
    public List<EsQuestion> queryByPathOnlyQuestion(final QaQueryDto qaQueryDto) throws Exception {
        {
            RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
            BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
            //只查询题库状态正常的数据
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_CATEGORY, qaQueryDto.getCategory()));
            boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL1TITLE2, qaQueryDto.getLevel1Title()));
            if (StringUtils.isNotBlank(qaQueryDto.getLevel2Title())) {
                boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL2TITLE2, qaQueryDto.getLevel2Title()));
            } else {
                //科目信息从配置查询，ES查询只要查问题即可
                BoolQueryBuilder shouldQueryBuilderForLevel2Title = QueryBuilders.boolQuery();
                shouldQueryBuilderForLevel2Title.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(FieldConstant.FIELD_LEVEL2TITLE2)));
                shouldQueryBuilderForLevel2Title.should(QueryBuilders.termsQuery(FieldConstant.FIELD_LEVEL2TITLE2, ""));
                boolqueryBuilder.must(shouldQueryBuilderForLevel2Title);
            }
            if (StringUtils.isNotBlank(qaQueryDto.getLevel3Title())) {
                boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL3TITLE2, qaQueryDto.getLevel3Title()));
            } else {
                //科目信息从配置查询，ES查询只要查问题即可
                BoolQueryBuilder shouldQueryBuilderForLevel3Title = QueryBuilders.boolQuery();
                shouldQueryBuilderForLevel3Title.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(FieldConstant.FIELD_LEVEL3TITLE2)));
                shouldQueryBuilderForLevel3Title.should(QueryBuilders.termsQuery(FieldConstant.FIELD_LEVEL3TITLE2, ""));
                boolqueryBuilder.must(shouldQueryBuilderForLevel3Title);
            }
            EsQueryUtils.appendDeptQuery(boolqueryBuilder, qaQueryDto);
            EsQueryUtils.appendRoleQuery(boolqueryBuilder, qaQueryDto);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.size(SystemConstant.DEFAULT_PAGE_SIZE);
            sourceBuilder.from(0);
            sourceBuilder.query(boolqueryBuilder);
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(esConfig.getIndexName());
            sourceBuilder.sort(FieldConstant.FIELD_ORDER, SortOrder.ASC);
            searchRequest.source(sourceBuilder);
            SearchResponse search = null;
            try {
                search = client.search(searchRequest, RequestOptions.DEFAULT);
            } catch (Exception e) {
                // 防止安全认证失败重试一次
                search = client.search(searchRequest, RequestOptions.DEFAULT);
            } finally {
                ElasticSearchPoolUtil.returnClient(client);
            }
            SearchHits hits1 = search.getHits();

            return ResponseUtils.esResultToList(hits1);
        }
    }

    @Override
    public String queryChat(final String queryText) throws Exception {
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        boolqueryBuilder.must(QueryBuilders.matchQuery(FieldConstant.FIELD_QUESTION +
                                                       FieldConstant.FIELD_KEYWORD, StringUtils.trim(queryText)));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getChatIndexName());
        searchRequest.source(sourceBuilder);
        SearchResponse search;
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        try {
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        if (search.getHits().getHits().length == 0) {
            return null;
        }
        String answer = null;
        String chatStr = search.getHits().getAt(0).getSourceAsString();
        if (StringUtils.isNotBlank(chatStr)) {
            Chat chat = GsonUtils.GSON.fromJson(chatStr, Chat.class);
            // 多个答案随机取一个
            int size = chat.getAnswer().size();
            if (size == 1) {
                answer = chat.getAnswer().get(0);
            } else {
                answer = chat.getAnswer().get(new SecureRandom().nextInt(size));
            }
        }
        return answer;
    }
    @Override
    public List<EsQuestion> queryExact(final QaQueryDto qaQueryDto) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        String text = qaQueryDto.getQueryText();
        //只查询题库状态正常的数据
        boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
        boolqueryBuilder.must(QueryBuilders.termsQuery(FieldConstant.FIELD_CATEGORY,
                                                       qaQueryDto.getCategoryList()));
        BoolQueryBuilder shouldQueryBuilder = QueryBuilders.boolQuery();
        shouldQueryBuilder.should(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL1TITLE2, text));
        shouldQueryBuilder.should(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL2TITLE2, text));
        shouldQueryBuilder.should(QueryBuilders.termQuery(FieldConstant.FIELD_LEVEL3TITLE2, text));
        shouldQueryBuilder.should(QueryBuilders.termQuery(FieldConstant.FIELD_QUESTION2, text));

        for(int i=1;  i< 10; i++) {
            shouldQueryBuilder.should(QueryBuilders.termQuery(FieldConstant.FIELD_EXACT_MATCH + i, text));
        }
        boolqueryBuilder.must(shouldQueryBuilder);
        EsQueryUtils.appendDeptQuery(boolqueryBuilder,qaQueryDto);
        EsQueryUtils.appendRoleQuery(boolqueryBuilder,qaQueryDto);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.size(SystemConstant.DEFAULT_PAGE_SIZE);
        sourceBuilder.from(0);
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getIndexName());
        sourceBuilder.sort(FieldConstant.FIELD_ORDER, SortOrder.ASC);
        searchRequest.source(sourceBuilder);
        SearchResponse search = null;
        try {
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        SearchHits hits1 = search.getHits();
        return ResponseUtils.esResultToList(hits1);
    }

    @Override
    public List<EsQuestion> queryByFixWordKey(final QaQueryDto qaQueryDto) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        //只查询题库状态正常的数据
        boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
        boolqueryBuilder.must(QueryBuilders.termsQuery(FieldConstant.FIELD_CATEGORY,
                                                       qaQueryDto.getCategoryList()));
        BoolQueryBuilder shouldQueryBuilder = QueryBuilders.boolQuery();
        String question = qaQueryDto.getQueryText();
        String searchText = "*" + question + "*";
        shouldQueryBuilder.should(QueryBuilders.wildcardQuery(FieldConstant.FIELD_LEVEL1TITLE2, searchText));
        shouldQueryBuilder.should(QueryBuilders.wildcardQuery(FieldConstant.FIELD_LEVEL2TITLE2, searchText));
        shouldQueryBuilder.should(QueryBuilders.wildcardQuery(FieldConstant.FIELD_LEVEL3TITLE2, searchText));
        shouldQueryBuilder.should(QueryBuilders.wildcardQuery(FieldConstant.FIELD_QUESTION2, searchText));
        shouldQueryBuilder.should(QueryBuilders.wildcardQuery(FieldConstant.FIELD_ANSWER2, searchText));
        boolqueryBuilder.must(shouldQueryBuilder);
        EsQueryUtils.appendDeptQuery(boolqueryBuilder,qaQueryDto);
        EsQueryUtils.appendRoleQuery(boolqueryBuilder,qaQueryDto);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //精确匹配返回所有，肯定不会超过1000条
        sourceBuilder.size(SystemConstant.DEFAULT_PAGE_SIZE);
        sourceBuilder.from(0);
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getIndexName());
        sourceBuilder.sort(FieldConstant.FIELD_ORDER, SortOrder.ASC);
        searchRequest.source(sourceBuilder);
        SearchResponse search;
        try {
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        SearchHits hits1 = search.getHits();
        return ResponseUtils.esResultToList(hits1);
    }

    @Override
    public List<EsQuestion> queryEsByTokenizer(final QaQueryDto qaQueryDto) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        String question = qaQueryDto.getQueryText();
        //只查询题库状态正常的数据
        boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
        boolqueryBuilder.must(QueryBuilders.termsQuery(FieldConstant.FIELD_CATEGORY,
                                                       qaQueryDto.getCategoryList()));
        BoolQueryBuilder shouldQueryBuilder = QueryBuilders.boolQuery();
        shouldQueryBuilder.should(QueryBuilders.matchQuery(FieldConstant.FIELD_LEVEL1TITLE, question));
        shouldQueryBuilder.should(QueryBuilders.matchQuery(FieldConstant.FIELD_LEVEL2TITLE, question));
        shouldQueryBuilder.should(QueryBuilders.matchQuery(FieldConstant.FIELD_LEVEL3TITLE, question));
        shouldQueryBuilder.should(QueryBuilders.matchQuery(FieldConstant.FIELD_ANSWER, question));
        shouldQueryBuilder.should(QueryBuilders.matchQuery(FieldConstant.FIELD_SEARCH_TEXT, question));
        shouldQueryBuilder.should(QueryBuilders.termsQuery(FieldConstant.FIELD_TAGS, question));
        boolqueryBuilder.must(shouldQueryBuilder);
        EsQueryUtils.appendDeptQuery(boolqueryBuilder,qaQueryDto);
        EsQueryUtils.appendRoleQuery(boolqueryBuilder,qaQueryDto);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.size(30);
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getIndexName());
        searchRequest.source(sourceBuilder);
        SearchResponse search = null;
        try {
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        SearchHits hits1 = search.getHits();
        return ResponseUtils.esResultToList(hits1);
    }

    @Override
    public List<EsQuestion> queryAll(final QaQueryDto qaQueryDto) throws Exception {
        RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
        BoolQueryBuilder boolqueryBuilder = QueryBuilders.boolQuery();
        //只查询题库状态正常的数据
        boolqueryBuilder.must(QueryBuilders.termQuery(FieldConstant.FIELD_STATUS, SystemConstant.VALID_STATUS));
        boolqueryBuilder.must(QueryBuilders.termsQuery(FieldConstant.FIELD_CATEGORY, qaQueryDto.getCategoryList()));
        EsQueryUtils.appendDeptQuery(boolqueryBuilder,qaQueryDto);
        EsQueryUtils.appendRoleQuery(boolqueryBuilder,qaQueryDto);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.size(SystemConstant.DEFAULT_PAGE_SIZE);
        sourceBuilder.from(0);
        sourceBuilder.query(boolqueryBuilder);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(esConfig.getIndexName());
        sourceBuilder.sort(SortBuilders.fieldSort(FieldConstant.FIELD_ORDER).unmappedType("long").order(SortOrder.ASC));
        searchRequest.source(sourceBuilder);
        SearchResponse search = null;
        try {
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 防止安全认证失败重试一次
            search = client.search(searchRequest, RequestOptions.DEFAULT);
        } finally {
            ElasticSearchPoolUtil.returnClient(client);
        }
        SearchHits hits1 = search.getHits();
        return ResponseUtils.esResultToList(hits1);
    }

    private static List<String> checkBulkResponse(final BulkResponse bulkItemResponses) {
        List<String> rs = new ArrayList<>();
        for (BulkItemResponse itemResponse : bulkItemResponses.getItems()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.info("dealBatch response id:{}, result:{}",itemResponse.getId(), itemResponse.isFailed());
            }
            if (itemResponse.isFailed()) {
                rs.add(itemResponse.getId() + " : " + itemResponse.getFailureMessage());
            }
        }
        return rs;
    }

    @Override
    public String maintain(final String jsonStr, final String endPoint, final String method) throws Exception {
        try (final RestHighLevelClient client = ElasticSearchPoolUtil.getClient();
             final RestClient lowLevelClient = client.getLowLevelClient();
             final NStringEntity entity = new NStringEntity(jsonStr, ContentType.APPLICATION_JSON)) {

            final Request request = new Request(method, endPoint);
            request.setEntity(entity);
            final Response rsp = lowLevelClient.performRequest(request);
            String resEntity = EntityUtils.toString(rsp.getEntity(), StandardCharsets.UTF_8);
            return resEntity;
        } catch (Exception e) {
            LOGGER.error("查询异常,jsonStr:{}, endPoint:{},method:{}", jsonStr, endPoint, method, e);
        }
        return null;
    }

}
